<?php

namespace App\Library;

use App\Library\Traits\RabbitMQTrait;
use Exception;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

class RabbitMQPub
{
    use RabbitMQTrait;

    /**
     * Desc:
     * @throws Exception
     */
    public static function send(array $arr = []): void
    {
        $mq = config('mq');
        $connection = self::connection($mq);
        $channel = self::channel($connection, $mq);
        $arr[config('app.name')] = 1;
        $message = new AMQPMessage(json_encode($arr, JSON_UNESCAPED_UNICODE), ['delivery_mode' => 2]);
        $delay = $arr['delay'] ?? 0;
        $message->set('application_headers', new AMQPTable(['x-delay' => $delay * 1000]));
        $channel->basic_publish($message, $mq['exchange']);
        try {
            $connection->close();
        } catch (Exception $e) {
            echo $e->getMessage() . PHP_EOL;
        }
    }
}
